#include "Common.h"
#include "Material.h"
#include "Utils/Util.h"
#include "Utils/Tokenizer.h"
#include "Graphics/ShaderProgram.h"

using namespace RayFrame;

Material::Material()
{
  m_texture = Texture::GetDefaultTexture();
  m_shader = ShaderProgram::GetDefaultShaderProgram();
}

Material::~Material()
{

}

void Material::Create(STRING name, Texture* texture, ShaderProgram* shader)
{
  assert(!name.empty() && texture && shader);
  m_name = name;
  m_texture = texture;
  m_shader = shader;
}

void Material::Begin()
{
  assert(m_texture && m_shader);

  m_texture->Begin();
  m_shader->Begin();
}

void Material::End()
{
  assert(m_texture && m_shader);

  m_shader->End();
  m_texture->End();
}

bool Material::LoadObjMaterial(STRING filename, Material& result)
{
  if(!SearchResource(filename, "/Meshes/"))
    return false;

  Tokenizer tok, lineTok;
  if (!tok.setFile(filename.c_str()))
  {
    char str[256];
    sprintf(str, "Couldn't open material\"%s\"", filename.c_str());
    ErrorMsg(str);
    return false;
  }

  char *str;

  while ((str = tok.next()) != NULL)
  {
    switch (str[0])
    {
    case '#':
      // ignoring comments
      break;
    case 'n':
      if(strcmp(str, "newmtl") == 0)
      {
        result.m_name = tok.nextLine();
      }
      break;
    case 'm':
      if(strcmp(str, "map_Kd") == 0)
      {
        STRING texFilename = tok.nextLine();
		    Trim(texFilename);
        result.m_texture = Texture::CreateFromFile(texFilename);
      }
    default:
      break;
    }
  }

  return true;
}
